package com.zx.ishopping.config;

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**'
 * 配置缓存过期时间
 */

@Configuration
@EnableCaching
public class CacheConfiguration {
    
    
    @Bean
    public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory){

        RedisCacheWriter cacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);
        //全局默认缓存过期时间
        RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofMinutes(60));//缓存过期时间 1  小时
        
        //为指定的缓存配置单独的过期时间
        Map<String, RedisCacheConfiguration> configMap = new HashMap<>();
        configMap.put("productList", RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofSeconds(60)));//缓存过期时间 1 分钟
        
        configMap.put("bestSaleProductList", RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofSeconds(60)));
        
        
        //创建缓存管理器
        return RedisCacheManager.builder(cacheWriter)
                .cacheDefaults(defaultCacheConfig)//全局默认配置
                .withInitialCacheConfigurations(configMap)//自定义缓存配置
                .build();
        
    }
    
}
